package com.example.testrecorder;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testrecorder.domain.Issue;
import com.example.testrecorder.domain.QueAndAns;
import com.example.testrecorder.domain.SelectItem;
import com.example.testrecorder.domain.User;
import com.example.testrecorder.utils.BitmapUtil;
import com.example.testrecorder.utils.CallSystemCameraOrAlbum;
import com.example.testrecorder.utils.LogUtil;
import com.example.testrecorder.utils.MyDialog;
import com.example.testrecorder.utils.MyTextWatcher;
import com.example.testrecorder.utils.SelectDialog;
import com.example.testrecorder.utils.ViewUtil;

import org.litepal.LitePal;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class EditIssueActivity extends BaseActivity implements AdapterView.OnItemSelectedListener,View.OnClickListener {
    private Toolbar toolbar;
    private int id;//问题的id
    private Spinner platformSp, frequencySp, severitySp, solvedSp;
    private EditText titleEt, contentEt;
    private TextView idTv, selectTv;
    private LinearLayout picLl;
    private ArrayList<String> platformList, frequencyList, severityList, solvedList;
    private String platform = "IOS和Android";
    private String frequency = "高";
    private String severity = "高";
    private String solved = "未解决";
    private Issue editedIssue;
    private SelectDialog selectDialog;
    private String imgPathStr = "";
    private ImageView iv;
    private View picLine;
    private File imgFile;
    private static final int CHOOSE_FROM_ALBUM = 2;
    private static final String TAG = "EditIssueActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_issue);
        initView();
    }

    private void initView() {
        picLl = findViewById(R.id.picLl);
        picLl.setOnClickListener(this);
        iv = findViewById(R.id.iv);
        picLine = findViewById(R.id.picLine);
        selectTv = findViewById(R.id.selectTv);
        idTv = findViewById(R.id.idTv);
        platformSp = findViewById(R.id.platformSp);
        frequencySp = findViewById(R.id.frequencySp);
        severitySp = findViewById(R.id.severitySp);
        solvedSp = findViewById(R.id.solvedSp);
        titleEt = findViewById(R.id.titleEt);
        titleEt.requestFocus();
        titleEt.addTextChangedListener(new MyTextWatcher(titleEt, this));
        contentEt = findViewById(R.id.contentEt);

        platformSp = findViewById(R.id.platformSp);
        platformList = new ArrayList<>();
        platformList.add("IOS和Android");
        platformList.add("IOS");
        platformList.add("Android");
        ArrayAdapter<String> platformAdapter = new ArrayAdapter<>(this, R.layout.issue_field_item, platformList);
        platformAdapter.setDropDownViewResource(R.layout.issue_field_item);
        platformSp.setAdapter(platformAdapter);
        platformSp.setOnItemSelectedListener(this);

        frequencyList = new ArrayList<>();
        frequencyList.add("高");
        frequencyList.add("中");
        frequencyList.add("低");
        ArrayAdapter<String> frequencyAdapter = new ArrayAdapter<>(this, R.layout.issue_field_item, frequencyList);
        frequencyAdapter.setDropDownViewResource(R.layout.issue_field_item);
        frequencySp.setAdapter(frequencyAdapter);
        frequencySp.setOnItemSelectedListener(this);

        severityList = new ArrayList<>();
        severityList.add("高");
        severityList.add("中");
        severityList.add("低");
        ArrayAdapter<String> severityAdapter = new ArrayAdapter<>(this, R.layout.issue_field_item, severityList);
        severityAdapter.setDropDownViewResource(R.layout.issue_field_item);
        severitySp.setAdapter(severityAdapter);
        severitySp.setOnItemSelectedListener(this);

        solvedList = new ArrayList<>();
        solvedList.add("未解决");
        solvedList.add("已解决");
        solvedList.add("无需解决");
        ArrayAdapter<String> solvedAdapter = new ArrayAdapter<String>(this, R.layout.issue_field_item, solvedList);
        solvedAdapter.setDropDownViewResource(R.layout.issue_field_item);
        solvedSp.setAdapter(solvedAdapter);
        solvedSp.setOnItemSelectedListener(this);

        id = getIntent().getIntExtra("id", -1);
        List<Issue> issues = LitePal.where("id=?", "" + id).find(Issue.class);
        if ((issues.size() == 1)) {
            editedIssue = issues.get(0);
            String platform = editedIssue.getPlatform();
            String frequency = editedIssue.getFrequency();
            String severity = editedIssue.getSeverity();
            String solved = editedIssue.getSolved();
            String title = editedIssue.getTitle();
            String content = editedIssue.getContent();
            String imgPath = editedIssue.getImgPath();
            if ("IOS和Android".equals(platform)) {
                platformSp.setSelection(0);
            } else if ("IOS".equals(platform)) {
                platformSp.setSelection(1);
            } else if ("Android".equals(platform)) {
                platformSp.setSelection(2);
            }
            if ("高".equals(frequency)) {
                frequencySp.setSelection(0);
            } else if ("中".equals(frequency)) {
                frequencySp.setSelection(1);
            } else if ("低".equals(frequency)) {
                frequencySp.setSelection(2);
            }
            if ("高".equals(severity)) {
                severitySp.setSelection(0);
            } else if ("中".equals(frequency)) {
                severitySp.setSelection(1);
            } else if ("低".equals(frequency)) {
                severitySp.setSelection(2);
            }
            if ("已解决".equals(solved)) {
                solvedSp.setSelection(0);
            } else if ("未解决".equals(frequency)) {
                solvedSp.setSelection(1);
            } else if ("无需解决".equals(frequency)) {
                solvedSp.setSelection(2);
            }

            idTv.setText("" + id);
            titleEt.setText(title);
            contentEt.setText(content);
            if (!TextUtils.isEmpty(imgPath)) {
                selectTv.setText(imgPath);
                imgPathStr=imgPath;
                Bitmap bitmapFromPath = BitmapUtil.getBitmapFromPath(imgPath);
                iv.setImageBitmap(bitmapFromPath);
                iv.setVisibility(View.VISIBLE);
                picLine.setVisibility(View.VISIBLE);
            } else {
                selectTv.setText("无，点击添加");
            }

        }
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        LogUtil.logD(TAG, "父布局的id：" + parent.getId());
        switch (parent.getId()) {
            case R.id.platformSp:
                platform = platformList.get(position);
                break;
            case R.id.frequencySp:
                frequency = frequencyList.get(position);
                break;
            case R.id.severitySp:
                severity = severityList.get(position);
                break;
            case R.id.solvedSp:
                solved = solvedList.get(position);
                break;
            default:
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.edit_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.save:
                editedIssue.setPlatform(platform);
                editedIssue.setFrequency(frequency);
                editedIssue.setSeverity(severity);
                editedIssue.setSolved(solved);
                editedIssue.setTitle(titleEt.getText().toString());
                editedIssue.setContent(contentEt.getText().toString());
                editedIssue.setImgPath(imgPathStr);
                editedIssue.setUpdateTime(new Date());//修改时间
                boolean save = editedIssue.save();
                if (save) {
                    Toast.makeText(EditIssueActivity.this, "保存成功！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(EditIssueActivity.this, IssueDetailActivity.class);
                    intent.putExtra("id",editedIssue.getId());
                    startActivity(intent);
                } else {
                    Toast.makeText(EditIssueActivity.this, "保存失败！", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.picLl) {
            ArrayList<SelectItem> list = new ArrayList<>();
            list.add(new SelectItem(R.drawable.icons8_google_images_96px, "拍照"));
            list.add(new SelectItem(R.drawable.icons8_picture_96px, "从相册中选择"));
            selectDialog = new SelectDialog(EditIssueActivity.this, list, new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (selectDialog != null) {
                        selectDialog.dismiss();
                    }
                    if (position == 0) {
                        if (Build.VERSION.SDK_INT >= 23) {//6.0以上版本，加入动态权限申请
                            int i1 = ContextCompat.checkSelfPermission(EditIssueActivity.this, Manifest.permission.CAMERA);
                            int i2 = ContextCompat.checkSelfPermission(EditIssueActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);//写权限包括了读权限
                            if (i1 != PackageManager.PERMISSION_GRANTED || i2 != PackageManager.PERMISSION_GRANTED) {//没有授予相机权限或读写权限
                                //请求读写权限、相机权限
                                ActivityCompat.requestPermissions(EditIssueActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                            } else {//授予了相机权限或读写权限
                                bootCamera();
                            }
                        } else {//6.0以下版本，直接打开相机
                            bootCamera();
                        }
                    } else if (position == 1) {
                        //如果未授予读写SD卡的权限
                        if (ContextCompat.checkSelfPermission(EditIssueActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(EditIssueActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CHOOSE_FROM_ALBUM);
                        } else {//授予了读写SD卡的权限
                            openAlbum();//打开相册
                        }
                    }
                }
            });
        }
    }

    /**
     * 打开相机
     */
    private void bootCamera() {
        imgFile = CallSystemCameraOrAlbum.OpenCamera(EditIssueActivity.this);//调用工具类来拍照
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_FROM_ALBUM); // 打开相册
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CallSystemCameraOrAlbum.CAMERA_REQUEST_CODE) {
            if (imgFile.exists()) {
                selectTv.setText(imgFile.getAbsolutePath());//将照片的存储路径显示到界面上
                imgPathStr = imgFile.getAbsolutePath();//给照片的路径变量赋值，以便将该路径保存到SQLite数据库
                LogUtil.logD(TAG, "图片的路径是：" + imgFile.getAbsolutePath());
                Bitmap bitmapFromPath = BitmapUtil.getBitmapFromPath(imgPathStr);
                iv.setImageBitmap(bitmapFromPath);
                iv.setVisibility(View.VISIBLE);
                picLine.setVisibility(View.VISIBLE);
            } else {
                Toast.makeText(EditIssueActivity.this, "您尚未完成拍照。", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == CHOOSE_FROM_ALBUM) {
            if (resultCode == RESULT_OK) {
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat(data);// 4.4 及以上系统使用这个方法处理图片
                } else {
                    handleImageBeforeKitKat(data);// 4.4 以下系统使用这个方法处理图片
                }
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是 document 类型的 Uri ，则通过 document id 处理
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的 id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.
                    getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 content 类型的 Uri ，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 file 类型的 Uri ，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath); // 根据图片路径显示图片
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过 Uri 和 和 selection 来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.
                        Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            selectTv.setText(imagePath);
            imgPathStr=imagePath;
            iv.setImageBitmap(bitmap);
            iv.setVisibility(View.VISIBLE);
            picLine.setVisibility(View.VISIBLE);
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }

}